﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;

namespace Library
{
    public class clsBackupHelper
    {
        public clsBackupHelper()
        {

        }

        public void BackupDatabase(String databaseName, String destinationPath)
        {
            try
            {
                Backup sqlBackup = new Backup();

                sqlBackup.Action = BackupActionType.Database;
                sqlBackup.BackupSetDescription = "ArchiveDataBase:" + DateTime.Now.ToShortDateString();
                sqlBackup.BackupSetName = "Archive";

                sqlBackup.Database = databaseName;
                BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath, DeviceType.File);

                Server SqlServer = new Server(Utils.Setting.ServerName);
                ServerConnection connection = SqlServer.ConnectionContext;
                connection.LoginSecure = true;
                connection.DatabaseName = "master";

                Database db = SqlServer.Databases[databaseName];
                sqlBackup.Initialize = true;
                sqlBackup.Checksum = true;
                sqlBackup.ContinueAfterError = true;

                sqlBackup.Devices.Add(deviceItem);
                sqlBackup.Incremental = false;

                //sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
                sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;

                sqlBackup.FormatMedia = false;
                sqlBackup.PercentCompleteNotification = 10;
                sqlBackup.PercentComplete += new PercentCompleteEventHandler(sqlBackup_PercentComplete);
                sqlBackup.Complete += new ServerMessageEventHandler(sqlBackup_Complete);
                sqlBackup.SqlBackup(SqlServer);
            }
            catch
            {
                throw;
            }
        }
        public event EventHandler<PercentCompleteEventArgs> PercentComplete;

        void sqlBackup_PercentComplete(object sender, PercentCompleteEventArgs e)
        {
            if (PercentComplete != null)
                PercentComplete(sender, e);
        }

        public event EventHandler<ServerMessageEventArgs> Complete;

        void sqlBackup_Complete(object sender, ServerMessageEventArgs e)
        {
            if (Complete != null)
                Complete(sender, e);
        }
    }
}
